package com.tbit.uqbike.webmanager.util.weixin;

import com.tbit.uqbike.object.pojo.WeixinPayConfig;
import com.tbit.uqbike.object.pojo.WeixinPayParam;
import com.tbit.uqbike.object.pojo.WxPayDto;
import com.tbit.utils.DateTimeUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.SortedMap;
import java.util.TreeMap;

/**
 * 微信支付
 *
 * @author Leon
 * 2015-11-10 下午04:57:38
 */
@Slf4j
public class WeixinPay {
    /**
     * 获取请求预支付id报文
     *
     * @return
     */
    @SuppressWarnings("static-access")
    public static String getPackage(WeixinPayConfig weixinPayConfig, WxPayDto tpWxPayDto) {
        String openId = tpWxPayDto.getOpenId();
        // 1 参数
        // 订单号
        String orderId = tpWxPayDto.getOrderId();
        // 附加数据 原样返回
        String attach = "";
        // 总金额以分为单位，不带小数点
        String totalFee = WeixinPayUtil.getMoney(tpWxPayDto.getTotalFee());

        // 订单生成的机器 IP
        String spbill_create_ip = tpWxPayDto.getSpbillCreateIp();
        // 这里notify_url是 支付完成后微信发给该链接信息，可以判断会员是否支付成功，改变订单状态等。
        String notify_url = weixinPayConfig.getNotifyUrl();
        String trade_type = "JSAPI";

        // ---必须参数
        // 商户号
        String mch_id = weixinPayConfig.getPartner();
        // 随机字符串
        String nonce_str = WeixinPayUtil.getNonceStr(false);

        // 商品描述根据情况修改
        String body = tpWxPayDto.getBody();

        // 商户订单号
        String out_trade_no = orderId;

        SortedMap<String, String> packageParams = new TreeMap<String, String>();
        packageParams.put("appid", weixinPayConfig.getAppId());
        packageParams.put("mch_id", mch_id);
        packageParams.put("nonce_str", nonce_str);
        packageParams.put("body", body);
        packageParams.put("attach", attach);
        packageParams.put("out_trade_no", out_trade_no);

        // 这里写的金额为1 分到时修改
        packageParams.put("total_fee", totalFee);
        packageParams.put("spbill_create_ip", spbill_create_ip);
        packageParams.put("notify_url", notify_url);

        packageParams.put("trade_type", trade_type);
        packageParams.put("openid", openId);

        String time_expire = DateTimeUtil.getNowTimeyyyyMMddHHmmss();
        /**添加交易截止时间*/
        packageParams.put("time_expire", time_expire);

        RequestHandler reqHandler = new RequestHandler(null, null);
        reqHandler.init(weixinPayConfig.getAppId(), weixinPayConfig.getSecret(), weixinPayConfig.getPartnerkey());

        String sign = reqHandler.createSign(packageParams);
        String xml = "<xml>"
                + "<appid>" + weixinPayConfig.getAppId() + "</appid>"
                + "<mch_id>" + mch_id + "</mch_id>"
                + "<nonce_str>" + nonce_str + "</nonce_str>"
                + "<sign>" + sign + "</sign>"
                + "<body><![CDATA[" + body + "]]></body>"
                + "<out_trade_no>" + out_trade_no + "</out_trade_no>"
                + "<attach>" + attach + "</attach>"
                + "<total_fee>" + totalFee + "</total_fee>"
                + "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>"
                + "<notify_url>" + notify_url + "</notify_url>"
                + "<trade_type>" + trade_type + "</trade_type>"
                + "<openid>" + openId + "</openid>"
                + "<time_expire>" + time_expire + "</time_expire>"
                + "</xml>";
        String prepay_id = "";
        String createOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";

        prepay_id = new GetWxOrderno().getPayNo(createOrderURL, xml);

        //获取prepay_id后，拼接最后请求支付所需要的package
        SortedMap<String, String> finalpackage = new TreeMap<String, String>();
        String timestamp = Sha1Util.getTimeStamp();
        String packages = "prepay_id=" + prepay_id;
        finalpackage.put("appId", weixinPayConfig.getAppId());
        finalpackage.put("timeStamp", timestamp);
        finalpackage.put("nonceStr", nonce_str);
        finalpackage.put("package", packages);
        finalpackage.put("signType", "MD5");
        //要签名
        String finalsign = reqHandler.createSign(finalpackage);

        String finaPackage = "'appId':'" + weixinPayConfig.getAppId() + "','timeStamp':'" + timestamp
                + "','nonceStr':'" + nonce_str + "','package':'"
                + packages + "','signType' : 'MD5" + "','paySign':'"
                + finalsign + "'";

        return finaPackage;
    }

    /**
     * 获取请求预支付id报文
     *
     * @return
     */
    @SuppressWarnings("static-access")
    public static WeixinPayParam getPackage_app(WeixinPayConfig weixinPayConfig, WxPayDto tpWxPayDto) {
        WeixinPayParam wpp = new WeixinPayParam();

        // 1 参数
        // 订单号
        String orderId = tpWxPayDto.getOrderId();
        // 附加数据 原样返回
        String attach = "";
        // 总金额以分为单位，不带小数点
        String totalFee = WeixinPayUtil.getMoney(tpWxPayDto.getTotalFee());

        // 订单生成的机器 IP
        String spbill_create_ip = tpWxPayDto.getSpbillCreateIp();
        // 这里notify_url是 支付完成后微信发给该链接信息，可以判断会员是否支付成功，改变订单状态等。
        String notify_url = weixinPayConfig.getNotifyUrl();
        String trade_type = "APP";

        // ---必须参数
        // 商户号
        String mch_id = weixinPayConfig.getPartner();
        // 随机字符串
        String nonce_str = WeixinPayUtil.getNonceStr(false);

        // 商品描述根据情况修改
        String body = tpWxPayDto.getBody();

        // 商户订单号
        String out_trade_no = orderId;

        SortedMap<String, String> packageParams = new TreeMap<String, String>();
        packageParams.put("appid", weixinPayConfig.getAppId());
        packageParams.put("mch_id", mch_id);
        packageParams.put("nonce_str", nonce_str);
        packageParams.put("body", body);
        packageParams.put("out_trade_no", out_trade_no);
        packageParams.put("attach", attach);
        packageParams.put("total_fee", totalFee);
        packageParams.put("spbill_create_ip", spbill_create_ip);
        packageParams.put("notify_url", notify_url);
        packageParams.put("trade_type", trade_type);

        RequestHandler reqHandler = new RequestHandler(null, null);
        reqHandler.init(weixinPayConfig.getAppId(), weixinPayConfig.getSecret(), weixinPayConfig.getPartnerkey());

        String sign = reqHandler.createSign(packageParams);
        String xml = "<xml>"
                + "<appid>" + weixinPayConfig.getAppId() + "</appid>"
                + "<mch_id>" + mch_id + "</mch_id>"
                + "<nonce_str>" + nonce_str + "</nonce_str>"
                + "<sign>" + sign + "</sign>"
                + "<body><![CDATA[" + body + "]]></body>"
                + "<out_trade_no>" + out_trade_no + "</out_trade_no>"
                + "<attach>" + attach + "</attach>"
                + "<total_fee>" + totalFee + "</total_fee>"
                + "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>"
                + "<notify_url>" + notify_url + "</notify_url>"
                + "<trade_type>" + trade_type + "</trade_type>"
                + "</xml>";
        String prepay_id = "";
        String createOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";

        /**调试打印*/
//		System.out.println(xml);
        prepay_id = new GetWxOrderno().getPayNo(createOrderURL, xml);

        //获取prepay_id后，拼接最后请求支付所需要的package
        SortedMap<String, String> finalpackage = new TreeMap<String, String>();
        String timestamp = Sha1Util.getTimeStamp();

        finalpackage.put("appid", weixinPayConfig.getAppId());
        finalpackage.put("partnerid", weixinPayConfig.getPartner());
        finalpackage.put("prepayid", prepay_id);
        finalpackage.put("package", "Sign=WXPay");
        finalpackage.put("noncestr", nonce_str);
        finalpackage.put("timestamp", timestamp);

        //生成签名
        String finalsign = reqHandler.createSign(finalpackage);

        wpp.setOrderNO(out_trade_no);
        wpp.setTotalFee(tpWxPayDto.getTotalFee());
        wpp.setPrepayid(prepay_id);
        wpp.setTimestamp(timestamp);
        wpp.setWxpackage("Sign=WXPay");
        wpp.setNoncestr(nonce_str);
        wpp.setSign(finalsign);

        return wpp;
    }

    /**
     * 押金退还
     *
     * @param weixinPayConfig
     * @param
     */
    @SuppressWarnings("static-access")
    public static Boolean return_deposit(WeixinPayConfig weixinPayConfig, String out_trade_no, String out_refund_no, String fee, String totalFee) {
        /**退款接口*/
        String createOrderURL = "https://api.mch.weixin.qq.com/secapi/pay/refund";

        // 随机字符串
        String nonce_str = WeixinPayUtil.getNonceStr(true);

        SortedMap<String, String> packageParams = new TreeMap<String, String>();
        packageParams.put("appid", weixinPayConfig.getAppId());
        packageParams.put("mch_id", weixinPayConfig.getPartner());
        packageParams.put("nonce_str", nonce_str);
        packageParams.put("out_refund_no", out_refund_no);
        packageParams.put("out_trade_no", out_trade_no);
        packageParams.put("refund_fee", fee);
        packageParams.put("total_fee", totalFee);

        log.info("退款接口的入参：{}", packageParams);

        RequestHandler reqHandler = new RequestHandler(null, null);
        reqHandler.init(weixinPayConfig.getAppId(), weixinPayConfig.getSecret(), weixinPayConfig.getPartnerkey());

        String sign = reqHandler.createSign(packageParams);
        String xml = "<xml>"
                + "<appid>" + weixinPayConfig.getAppId() + "</appid>"
                + "<mch_id>" + weixinPayConfig.getPartner() + "</mch_id>"
                + "<nonce_str>" + nonce_str + "</nonce_str>"
                + "<out_refund_no>" + out_refund_no + "</out_refund_no>"
                + "<out_trade_no>" + out_trade_no + "</out_trade_no>"
                + "<refund_fee>" + fee + "</refund_fee>"
                + "<total_fee>" + totalFee + "</total_fee>"
                + "<sign>" + sign + "</sign>"
                + "</xml>";
        return GetWxOrderno.return_deposit(weixinPayConfig.getAccountId().toString(), weixinPayConfig.getType(), createOrderURL, xml, weixinPayConfig.getPartner(), out_trade_no);
    }


    public static Boolean returnMoney(WeixinPayConfig weixinPayConfig, String out_trade_no, String out_refund_no, String refund_fee, String fee) {
        /**退款接口*/
        String createOrderURL = "https://api.mch.weixin.qq.com/secapi/pay/refund";

        // 随机字符串
        String nonce_str = WeixinPayUtil.getNonceStr(true);

        SortedMap<String, String> packageParams = new TreeMap<String, String>();
        packageParams.put("appid", weixinPayConfig.getAppId());
        packageParams.put("mch_id", weixinPayConfig.getPartner());
        packageParams.put("nonce_str", nonce_str);
        packageParams.put("out_refund_no", out_refund_no);
        packageParams.put("out_trade_no", out_trade_no);
        packageParams.put("refund_fee", refund_fee);
        packageParams.put("total_fee", fee);
        RequestHandler reqHandler = new RequestHandler(null, null);
        reqHandler.init(weixinPayConfig.getAppId(), weixinPayConfig.getSecret(), weixinPayConfig.getPartnerkey());

        String sign = reqHandler.createSign(packageParams);
        String xml = "<xml>"
                + "<appid>" + weixinPayConfig.getAppId() + "</appid>"
                + "<mch_id>" + weixinPayConfig.getPartner() + "</mch_id>"
                + "<nonce_str>" + nonce_str + "</nonce_str>"
                + "<out_refund_no>" + out_refund_no + "</out_refund_no>"
                + "<out_trade_no>" + out_trade_no + "</out_trade_no>"
                + "<refund_fee>" + refund_fee + "</refund_fee>"
                + "<total_fee>" + fee + "</total_fee>"
                + "<sign>" + sign + "</sign>"
                + "</xml>";
        return GetWxOrderno.return_deposit(weixinPayConfig.getAccountId().toString(), weixinPayConfig.getType(), createOrderURL, xml, weixinPayConfig.getPartner(), out_trade_no);
    }

}
